import React, { PureComponent } from "react";
import {
  Text,
  View,
  Image,
  TextInput,
  Alert,
  ScrollView,
  FlatList,
  Platform,
  DeviceEventEmitter,
  TouchableOpacity,
  Keyboard,
  StyleSheet,
  RefreshControl
} from "react-native";
import { safeAreaBottomHeight, SureGoods } from "../../util/AdapterUtil";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import image from "../../assets/image";
import FlatListEmpty from "../../components/FlatListEmpty";
import NavigationService from "../../components/NavigationService";
import PaySelectAlertView from "../../components/payselectdialog/PaySelectAlertView";
import XPay from "react-native-puti-pay";
import ImageView from "../../components/ImageView";
import * as requestApi from "../../util/requestApi";

import _ from "lodash";
/*{
    "billRecordAmount": 0,
    "payTimeDesc": "最后还款日MAY月10号",
    "billRecordOrderVoList": [],
    "billId": ["ZD201905151320004QSEDZY2PPN16VYU", "ZD201905151320004QSEDZY2PPN16VYQ"]
}*/
class MBillScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      index: 0, //0已出账单 1未出账单
      listOfFinishedBill: [],
      data: [],
      owe: 0, //欠款多少
      billId: null,
      payTimeDesc: null,
      canClick: true,
      canPayBtnClicked: false,
    };
  }

  componentDidMount() {
    const tabIndex = _.get(this.props, 'navigation.state.params.tabIndex');
    if (tabIndex && _.isNumber(tabIndex)) {
      this.getData(tabIndex);
      this.setState({
        index: tabIndex,
      });
      return;
    }

    this.getData(0);

    //注册事件监听
    // this.deEmitter = DeviceEventEmitter.addListener(SureGoods, res => {
    //   this.getData(tabIndex);
    // });
  }

  componentWillUnmount() {
    //this.deEmitter && this.deEmitter.remove();
  }

  render() {
    return (
      <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"付款账单"}
          // isDrawer={() => {
          //   NavigationService.reset("Drawer");
          // }}
        />

        <View
          style={{
            padding: 10,
            backgroundColor: "#fff",
            flexDirection: "row",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <TouchableOpacity
            style={{
              flex: 1,
              backgroundColor: "#fff",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              this.setState({
                data: [],
                index: 0
              });
              this.getData(0);
            }}
            disabled={!this.state.canClick}
          >
            <Text
              style={{
                color: this.state.index === 0 ? "#4A90E2" : "#606060",
                fontSize: 14
              }}
            >
              已出账
            </Text>
            <View
              style={{
                marginTop: 5,
                width: 30,
                height: 2,
                backgroundColor:
                  this.state.index === 0 ? "#4A90E2" : "#00000000"
              }}
            />
          </TouchableOpacity>

          <View style={{ width: 1, height: 15, backgroundColor: "#CCCCCC" }} />

          <TouchableOpacity
            style={{
              padding: 10,
              flex: 1,
              backgroundColor: "#fff",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              this.setState({
                data: [],
                index: 1
              });
              this.getData(1);
            }}
            disabled={!this.state.canClick}
          >
            <Text
              style={{
                color: this.state.index === 1 ? "#4A90E2" : "#606060",
                fontSize: 14
              }}
            >
              未出账
            </Text>
            <View
              style={{
                marginTop: 5,
                width: 30,
                height: 2,
                backgroundColor:
                  this.state.index === 1 ? "#4A90E2" : "#00000000"
              }}
            />
          </TouchableOpacity>
        </View>
        <View
          style={{ width: "100%", height: 6, backgroundColor: "#F9F9F9" }}
        />
        {/*欠款金额*/}
        {this.state.index === 1
          ? this.state.data.length > 0
            ? null
            : this._renderpayoff()
          : this.state.owe === 0
          ? this._renderpayoff()
          : this._renderOwe()}

        <View
          style={{ width: "100%", height: 6, backgroundColor: "#F9F9F9" }}
        />
        <ScrollView style={{ flex: 1 }} alwaysBounceVertical={true}>
          <FlatList
            style={{ backgroundColor: "#fff" }}
            scrollEnabled={false}
            data={this.state.data}
            horizontal={false}
            keyExtractor={(item, index) => index.toString()}
            renderItem={this._renderItem}
          />
        </ScrollView>
        {this.state.data != null &&
        this.state.data.length > 0 &&
        (this.state.canPayBtnClicked) ? (
          <TouchableOpacity
            style={{
              marginTop: 20,
              marginLeft: 20,
              marginRight: 20,
              marginBottom: 20,
              height: 45,
              borderRadius: 6,
              backgroundColor: "#fff",
              borderWidth: 1,
              borderColor: "#4A90E2",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={this.payMoney.bind(this)}
          >
            <Text
              style={{
                color:
                  this.state.canPayBtnClicked
                    ? "#4A90E2"
                    : "#fff",
                fontSize: 14
              }}
            >
              {this.state.index === 0 ? "立即还款" : "提前还款"}
            </Text>
          </TouchableOpacity>
        ) : (
          <View
            style={{
              marginTop: 20,
              marginLeft: 20,
              marginRight: 20,
              marginBottom: 20,
              height: 45,
              borderRadius: 6,
              backgroundColor: "#ccc",
              borderWidth: 1,
              borderColor: "#ccc",
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text
              style={{
                color:
                this.state.canPayBtnClicked
                    ? "#4A90E2"
                    : "#fff",
                fontSize: 14
              }}
            >
              {this.state.index === 0 ? "立即还款" : "提前还款"}
            </Text>
          </View>
        )}
        <PaySelectAlertView
          ref={view => {
            this.payalert = view;
          }}
          onDone={res => {
            this.pay(res);
          }}
        />
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  _renderOwe = () => {
    return (
      <View
        style={{
          padding: 10,
          width: "100%",
          backgroundColor: "#fff",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <Text style={{ marginTop: 10, color: "#606060", fontSize: 14 }}>
          待还金额(元)
        </Text>
        <Text style={{ marginTop: 10, color: "#D0021B", fontSize: 25 }}>
          {this.state.owe}
        </Text>
        <Text style={{ marginTop: 5, color: "#606060", fontSize: 14 }}>
          {this.state.payTimeDesc}
        </Text>
      </View>
    );
  };

  _renderpayoff = () => {
    return (
      <View
        style={{
          padding: 10,
          width: "100%",
          backgroundColor: "#fff",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <Text style={{ marginTop: 10, color: "#606060", fontSize: 14 }}>
          待还金额(元)
        </Text>
        <Text style={{ marginTop: 10, color: "#D0021B", fontSize: 25 }}>0</Text>
        <Text style={{ marginTop: 10, color: "#000000", fontSize: 20 }}>
          本期账单已还清
        </Text>
        <Text>每月1日出账10日还款</Text>
      </View>
    );
  };

  //吊起支付
  payMoney() {
    const { index, listOfFinishedBill } = this.state;

    if (index === 1 && listOfFinishedBill.length !== 0) {
      Toast.show("清先还清已出账账单！", 1000);
      return;
    }

    if (
      this.state.data != null &&
      this.state.data.length > 0 &&
      (this.state.index == 1 || this.state.owe > 0)
    ) {
      this.payalert.show();
    } else {
      Toast.show("你没有账单，无需还款", 1000);
    }
  }
  //吊起支付宝支付
  alipay = data => {
    //设置    支付宝URL Schemes ios 必须设置 和原生匹配 ap + 支付宝应用id
    XPay.setAlipayScheme("ap2019051564640248")
    //支付宝开启沙箱模式 仅限安卓
    //XPay.setAlipaySandbox(isSandBox)
    // orderInfo是后台拼接好的支付参数
    XPay.alipay(data, res => {
      console.log("ali返回值：" + res);
      this.getData(this.state.index);
    });
  };
  //吊起支付宝支付
  wxpay = data => {
    //设置微信ID
    XPay.setWxId(data.appId);
    /*{
            "appId": "wx6c334440a8766ddf",
            "orderID": "Wx20190527150933KWWB0R96EOJGKYGL",
            "orderState": "0",
            "prepayId": "wx271509336114555b41b462994468932000",
            "partnerId": 1512655481,
            "nonceStr": "tQHb66fO8CvK7pqe",
            "timeStamp": "1558940973",
            "sign": "F7F92E839B3F3B253E85F913AED67654",
            "errormsg": "0"
        }*/
    let params = {
      prepayId: data.prepayId,
      partnerId: data.partnerId + "",
      nonceStr: data.nonceStr,
      packageValue: "Sign=WXPay",
      timeStamp: data.timeStamp,
      sign: data.sign
    };

    XPay.wxPay(params, res => {
      console.log("wx返回值：" + res);
      this.getData(this.state.index);
    });
  };

  //提前还款和立即还款
  pay = mode => {
    if (this.state.index === 1) {
      //提前还款
      requestApi
        .prepayment({ payMode: mode })
        .then(data => {
          switch (mode) {
            case 0:
              this.alipay(data);
              break;
            case 1:
              this.wxpay(data);
              break;
            case 2:
              Toast.show("还款成功", 1000);
              this.getData(1);
              break;
          }
        })
        .catch(err => {
           Toast.show(err.msg, 1000);
        });
    } else {
      //立即还款
      requestApi
        .immediateRepayment({ payMode: mode, billIds: this.state.billId })
        .then(data => {
          switch (mode) {
            case 0:
              this.alipay(data);
              break;
            case 1:
              this.wxpay(data);
              break;
            case 2:
              Toast.show("还款成功", 1000);
              this.getData(0);
              break;
          }
        })
        .catch(err => {
          Toast.show(err.msg, 1000);
        });
    }
  };

  getData = index => {
    this.setState({
        canClick: false,
    });
    if (index === 0) {
      requestApi
        .queryBill()
        .then(data => {
          // alert(JSON.stringify(data.billRecordOrderVoList, null, 2));
          const canPayBtnClicked = _.some(data.billRecordOrderVoList, (item) => item.receiveGoodsState === 1);
          this.setState({
            canPayBtnClicked,
            canClick: true,
            data: data.billRecordOrderVoList ? data.billRecordOrderVoList : [],
            listOfFinishedBill: _.isArray(data.billRecordOrderVoList)
              ? data.billRecordOrderVoList
              : [],
            owe: data.billRecordAmount ? data.billRecordAmount : 0,
            payTimeDesc: data.payTimeDesc ? data.payTimeDesc : "",
            billId: data.billId
          });
        })
        .catch(err => {
          this.setState({
            data: [],
            canClick: true,
          });
          Toast.show(err.msg, 1000);
        });
    } else {
      requestApi
        .queryYetGeneratedBill()
        .then(data => {
          const canPayBtnClicked = _.some(data.billRecordOrderVoList, (item) => item.receiveGoodsState === 1);
          this.setState({
            canPayBtnClicked,
            canClick: true,
            data: data.billRecordOrderVoList
          });
        })
        .catch(err => {
          this.setState({
            canClick: true,
            data: []
          });
          Toast.show(err.msg, 1000);
        });
    }
  };

  _renderItem = ({ item }) => (
    <BillItem onPressItem={this._onPressItem.bind(this)} item={item} />
  );

  _onPressItem = id => {
    let {index} =  this.state
    NavigationService.navigate("MBillDetailScreen", {
      orderId: id,
      reloadList: this.getData.bind(this, index)
    });
  };
}

class BillItem extends PureComponent {
  _onPress = () => {
    this.props.onPressItem(this.props.item.orderId);
  };

  /*{
        companyName: "测试11111111111",
        payTime: "2019-05-24T02:25:52.000+0000",
        amount: 1,
        refundStatus: false,
        payMode: 1,
        receiveGoodsState:1
    }*/

  render() {
    return (
      <View style={{ height: 61 }}>
        <TouchableOpacity
          style={{
            flexDirection: "row",
            height: 60,
            marginLeft: 10,
            marginTop: 2,
            marginRight: 10,
            marginBottom: 2,
            alignItems: "center"
          }}
          onPress={this._onPress.bind(this)}
        >
          <View
            style={{
              flex: 1,
              marginLeft: 10,
              paddingTop: 2,
              marginRight: 10,
              paddingBottom: 2,
              justifyContent: "center",
              alignItems: "flex-start"
            }}
          >
            <Text style={{ color: "#606060", fontSize: 14 }} numberOfLines={1}>
              {this.props.item.companyName}
            </Text>
            <View style={{ height: 12 }} />
            <Text style={{ color: "#AAAAAA", fontSize: 12 }} numberOfLines={1}>
              {this.props.item.payTime}
            </Text>
          </View>
          <View
            style={{
              flex: 1,
              marginLeft: 10,
              paddingTop: 2,
              marginRight: 10,
              paddingBottom: 2,
              justifyContent: "center",
              alignItems: "flex-end"
            }}
          >
            <Text style={{ color: "#606060", fontSize: 14 }} numberOfLines={1}>
              ¥ {this.props.item.amount}
            </Text>
            <Text
              numberOfLines={1}
              style={[
                this.props.item.refundStatus
                  ? { color: "#F79646" }
                  : { color: "#AAAAAA" },
                { fontSize: 12 }
              ]}
            >
              {this.props.item.refundStatus ? "有退款" : null}
            </Text>
            <View style={{ flexDirection: "row" }}>
              <Text
                numberOfLines={1}
                style={[{ color: "#AAAAAA" }, { fontSize: 12 }]}
              >
                {this.props.item.payState === 1 ? "已支付" : "已关闭"}
              </Text>

              <Text
                numberOfLines={1}
                style={[{ color: "#AAAAAA" }, { fontSize: 12 }]}
              >
                {this.props.item.payMode === 2 ? "、货到付款" : null}
              </Text>
              <Text
                numberOfLines={1}
                style={[{ color: "#AAAAAA" }, { fontSize: 12 }]}
              >
                {this.props.item.receiveGoodsState === 0 ? "、待收货" : '、已收货'}
              </Text>
            </View>
          </View>
        </TouchableOpacity>

        <View
          style={{
            marginLeft: 20,
            height: 1,
            backgroundColor: "#DDDDDD",
            transform: [{ scaleY: 0.5 }]
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {}
)(MBillScreen);
